package com.dmap.admin.controller.backgroundv2;

import com.dmap.admin.constants.AdminConstant;
import com.dmap.admin.controller.backgroundv2.param.LoginV2Param;
import com.dmap.admin.controller.backgroundv2.param.UserV2Param;
import com.dmap.admin.po.Company;
import com.dmap.admin.po.LoginLog;
import com.dmap.admin.po.User;
import com.dmap.admin.service.backgroundv2.CompanyService;
import com.dmap.admin.service.backgroundv2.IdentifyingCodeService;
import com.dmap.admin.service.backgroundv2.LoginLogService;
import com.dmap.admin.service.backgroundv2.UserV2Service;
import com.dmap.admin.vo.backgroundv2.LoginVo;
import com.dmap.base.constants.Constant;
import com.dmap.base.units.MD5Util;
import com.dmap.base.vo.BaseVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * \* User: helei
 * \* Date: 04/05/18
 * \* Description:
 * \
 */
@Api(value = "个人数据服务系统用户登录", description = "background/个人数据服务系统用户登录")
@Controller
@RequestMapping(value = "/background/pmpd-admin-server/v2/user/login/")
public class LoginV2Controller {

    @Resource
    private UserV2Service userV2Service;
    @Resource
    private LoginLogService loginLogService;
    @Resource
    private CompanyService companyService;
    @Resource
    private IdentifyingCodeService identifyingCodeService;

    @ResponseBody
    @ApiOperation(value = "个人数据服务系统用户登录",
            notes = "1.必填(2选1)： 用户账号account 或者 手机号handphone;" +
                    "2.必填: 密码password;" +
                    "3.返回用户登陆信息;")
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public BaseVo login(@RequestBody LoginV2Param param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || (StringUtils.isBlank(param.getAccount()) && StringUtils.isBlank(param.getHandphone()))
                || StringUtils.isBlank(param.getPassword())) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        User user = userV2Service.selectByLoginV2Param(param.getAccount(), param.getHandphone());
        //数据库查询是不区分大小写的，所以要加后面两个判断
        if (user == null || (!user.getAccount().equals(param.getAccount()) && !user.getHandphone().equals(param.getHandphone()))) {
            baseVo.setCode(AdminConstant.RESPONSE_LOGIN_V2_ACCOUNT_ERROR_CODE);
            baseVo.setMsg(AdminConstant.RESPONSE_LOGIN_V2_ACCOUNT_ERROR_MSG);
            return baseVo;
        }
        //没有启用的用户，不能登录系统
        if (!user.getStatus().equals(AdminConstant.NORMAL_STATUS)) {
            baseVo.setCode(AdminConstant.RESPONSE_USER_STATUS_ERROR_CODE);
            baseVo.setMsg(AdminConstant.RESPONSE_USER_STATUS_ERROR_MSG);
            return baseVo;
        }
        //所属公司已禁用，公司所有成员不能登录本系统
        Company company = companyService.selectById(user.getCompanyId());
        if (company != null && company.getStatus() != null && company.getStatus() == AdminConstant.FORBID_STATUS) {
            baseVo.setCode(AdminConstant.RESPONSE_COMPANY_STATUS_ERROR_CODE);
            baseVo.setMsg(AdminConstant.RESPONSE_COMPANY_STATUS_ERROR_MSG);
            return baseVo;
        }
        //登录错误次数已达到五次，账号已被封锁，请联系管理员
        if (user.getLoginWrongNum() > (AdminConstant.MAX_LOGIN_WRONG_NUM)) {
            baseVo.setCode(AdminConstant.RESPONSE_LOGIN_WRONG_NUM_ERROR_CODE);
            baseVo.setMsg(AdminConstant.RESPONSE_LOGIN_WRONG_NUM_ERROR_MSG);
            return baseVo;
        }
        //密码错误
        String tempMD5Password = MD5Util.md5Password(param.getPassword());
        if (!user.getPassword().equals(tempMD5Password)) {
            baseVo.setCode(AdminConstant.RESPONSE_LOGIN_V2_PW_ERROR_CODE);
            baseVo.setMsg(AdminConstant.RESPONSE_LOGIN_V2_PW_ERROR_MSG);
        }
        //以下几个数据用于插入登陆日志
        LoginVo loginVo = new LoginVo(user);
        loginVo.setIp(param.getIp());
        loginVo.setAddress(param.getAddress());
        loginVo.setThisLoginTime(System.currentTimeMillis() / 1000);
        LoginLog loginLog = loginLogService.selectLastLogByUserId(user.getId());
        if (loginLog != null) {
            loginVo.setLastLoginTime(loginLog.getCreateTime());
        }
        baseVo.setData(loginVo);
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "用户登录忘记并修改密码",
            notes = "1.必填： 手机号 handphone, 验证码 code, 密码 password; " +
                    "2.返回成功;")
    @RequestMapping(value = "login/updatePassword", method = RequestMethod.GET)
    public BaseVo updatePassword(@RequestParam String handphone,
                                 @RequestParam String code,
                                 @RequestParam String password) {
        BaseVo baseVo = new BaseVo();
        if ((StringUtils.isBlank(handphone) && StringUtils.isBlank(password))
                || StringUtils.isBlank(code)) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        String value = identifyingCodeService.getIdentifyingCode(handphone);
        //手机号错误或者验证码已失效（验证码有效期10分钟）
        if (StringUtils.isBlank(value)) {
            baseVo.setCode(AdminConstant.RESPONSE_CODE_VALIDATE_ERROR_CODE);
            baseVo.setMsg(AdminConstant.RESPONSE_CODE_VALIDATE_ERROR_MSG);
            return baseVo;
        }
        //验证码错误
        if (!value.equals(code)) {
            baseVo.setCode(AdminConstant.RESPONSE_CODE_WRONG_ERROR_CODE);
            baseVo.setMsg(AdminConstant.RESPONSE_CODE_WRONG_ERROR_MSG);
            return baseVo;
        }
        User user = userV2Service.selectByAccountOrHandphone(handphone);
        //数据库查询是不区分大小写的，所以要加后面两个判断
        if (user == null || !user.getHandphone().equals(handphone)) {
            baseVo.setCode(AdminConstant.RESPONSE_LOGIN_V2_ACCOUNT_ERROR_CODE);
            baseVo.setMsg(AdminConstant.RESPONSE_LOGIN_V2_ACCOUNT_ERROR_MSG);
            return baseVo;
        }
        //修改密码，并将登陆错误次数置0
        UserV2Param userV2Param = new UserV2Param();
        userV2Param.setId(user.getId().toString());
        userV2Param.setPassword(password);
        userV2Param.setLoginWrongNum(0);
        boolean success = userV2Service.updateUser(userV2Param);
        if (!success) {
            baseVo.setCode(Constant.RESPONSE_UPDATE_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_UPDATE_ERROR_MSG);
        }
        return baseVo;
    }

}